<template>
    <div class="MUser-list">
        <div class="MUser-name" v-for="(user,index) in initUsers" :key="index">
            <my-icon class="user-icon" size="0.7rem" type="icon-people"></my-icon>
            <span class="MUser-fullName">{{ user.fullName }}</span>
            <my-icon class="user-del" v-if="!readOnly" @click="onDelete(index)" size="0.9rem"
                     type="icon-icon-test26"></my-icon>
        </div>
        <div class="MUser-chang" @click="onChange" v-if="!readOnly">
            <my-icon size="1rem" type="icon-jia"></my-icon>
        </div>
    </div>
    <RxEmpty v-if="readOnly && initUsers.length==0"></RxEmpty>
</template>

<script>
/*
用户控件
 */
import MForm from '../js/MForm'
import Util from "../../../../js/Util";
import Dialog from "@/js/Dialog";
import RxEmpty from "@/components/RxEmpty";
import Api from "@/api/Api";

export default {
    name: "MUser",
    mixins: [MForm],
    components:{RxEmpty},
    data() {
        return {
            userList: [],//选中用户列表全部数据
            initUsers: [],//选中渲染用户列表
            tenantId: '',//租户ID
            dimIds: "1",//指定维度ID,默认为1
            single: false,//单选多选
            showDepPath: this.metadata.options.showDepPath,//是否显示全路径
            randomId: Util.randomId(),
            curVal: '',
        }
    },
    created() {
        if (this.metadata) {
            let options = this.metadata.options
            this.dimIds = options.orgGroupConfig.dimId ? options.orgGroupConfig.dimId : this.dimIds
            this.single = options.single
            this.showDepPath = options.showDepPath
            this.updateCurValPath()
        }
    },
    methods: {
        i18n(name,text,key){
            return this.$ti18(name,text,"componentsLang",key);
        },
        initUser() {
            this.initUsers = [];
            if (!this.curVal) {
                return
            }
            let obj = JSON.parse(this.curVal)
            if (this.single) {
                this.initUsers = [{
                    userId: obj.value,
                    fullName: obj.label
                }];
            } else {
                let values = obj.value.split(",");
                let labels = obj.label.split(",");
                for (let i = 0; i < values.length; i++) {
                    this.initUsers.push({
                        userId: values[i],
                        fullName: labels[i],
                    })
                }
            }
        },
        async updateCurValPath() {
            if (!this.showDepPath) {
                return;
            }
            await this.initUserDepPathName(this.initUsers)
            for (let curUser of this.initUsers) {
                curUser.fullName += '[' + curUser.deptPathName + ']'
            }

            this.curVal = JSON.stringify({
                "label": this.initUsers.map(user => user.fullName).join(","),
                "value": this.initUsers.map(user => user.userId).join(",")
            })
            this.setValue(this.curVal)
        },
        /*
        删除
         */
        onDelete(index) {
            this.initUsers.splice(index, 1);
            if (this.initUsers.length == 0) {
                this.curVal = '';
            }else {
                let values = [];
                let labels = [];
                this.initUsers.forEach(res => {
                    values.push(res.userId);
                    labels.push(res.fullName)
                })
                let newValue = JSON.stringify({
                    value: values.join(","),
                    label: labels.join(","),
                })
                this.curVal = newValue
            }
            this.setValue(this.curVal)
        },
        onChange() {
            let config = this.getGroupConfig();
            if (!config) {
                return
            }
            // 将 用户名[xxxx]的[xxxx]去掉
            this.initUsers.filter(user=>user.userId).map(user=>{
                if (user.fullName.indexOf("[") > -1 && user.fullName.endWith("]")) {
                    user.fullName = user.fullName.substring(0, user.fullName.indexOf("["));
                }
                return user;
            })
            let conf = {
                data: {
                    value: this.initUsers,
                    'single': this.single,
                    'dimIds':this.dimIds,
                    'tenantId':this.tenantId,
                    'randomId':this.randomId,
                    ...config,
                },
                curVm: this
            };
            Dialog.openUserDialog(conf, (data) => {
                this.userOK(data)
            })
        },
        /**
         *获取组织配置
         */
        getGroupConfig(){
            let obj={
                groupId:"",
                showDimId:false
            }
            let config=this.metadata.options;

            obj.orgconfig = config.orgGroupType
            //当前组织
            if(config.orgGroupType=='curOrg'){
                obj.groupId="curOrg";
            }else if(config.orgGroupType=='selOrg'){
                //指定组织
                obj.groupId=config.orgGroupConfig?JSON.parse(config.orgGroupConfig).value:"";
            }else if(config.orgGroupType=='allOrg'){
                //所有组织
                if(!config.orgGroupConfig.dimId){
                    obj.showDimId=true;
                }
                obj.dimId=config.orgGroupConfig.dimId || "1";
                obj.initRankLevel=config.orgGroupConfig.initRankLevel;
            }else if(config.orgGroupType=='relOrg'){
                //关联组织
                let _groupId = this.getGroupId(config);
                if(_groupId == 'no'){ return }
                obj.groupId = _groupId
            }else {
                obj.showDimId=true;
            }
            return obj;
        },
        getGroupId(config){
            let groupId = '' ;
            let {field,gridName,valMode,name}=config.orgGroupConfig;
            if (!field) {
                uni.showToast({
                    title:this.i18n('associatedFields','未配置关联字段！'),
                    duration: 2000,
                    icon:'error'
                });
                return 'no';
            }
            if(this.metadata.subTable && gridName == 'main'){//如果控件在子表里面，并且关联主表里面的控件
                groupId = this.formVm.data[field] ;
            }else {
                groupId = this.data[field];
            }
            if (!groupId) {
                uni.showToast({
                    title:this.i18n('relatedFields','关联字段')+"【" + name + "】"+this.i18n('NoChoice','没有选择！'),
                    duration: 2000,
                    icon:'error'
                });
                return 'no';
            }
            if (valMode == "double") {
                groupId = JSON.parse(groupId).value;
            }
            return groupId ;
        },
        async userOK(curValue) {
            if (this.showDepPath) {
                await this.initUserDepPathName(curValue)
            }
            this.userList = curValue;
            if (curValue.length == 0) {
                this.curVal = ''
            } else {
                let newValue = "";
                if (this.single) {
                    //单选
                    let obj = curValue[0]
                    newValue = this.joinedPath(obj, this.showDepPath)
                    this.curVal = JSON.stringify(newValue)
                } else {
                    //多选
                    if (curValue) {
                        let values = [];
                        let labels = [];
                        for (let i = 0; i < curValue.length; i++) {
                            let obj = this.joinedPath(curValue[i], this.showDepPath)
                            values.push(obj.value);
                            labels.push(obj.label);
                        }
                        newValue = JSON.stringify({
                            value: values.join(","),
                            label: labels.join(","),
                        })
                        this.curVal = newValue
                    }
                }
            }
            this.setValue(this.curVal)
        },
        async initUserDepPathName(curValue) {
            let userIds = curValue.filter(user => !user.deptPathName).map(user => user.userId).join(",");
            if (!userIds) {
                return;
            }
            let res = await Api.getMainDepsByUserIds(userIds)
            if (!res.success) {
                return
            }
            let data = res.data
            for (let v of curValue) {
                if (data[v.userId]) {
                    v.deptPathName = data[v.userId];
                }
            }
        },
        setValue(value){
            this.updateValue(this.curVal);
            this.triggerEmitEvents('change', this.curVal, this.data)
        },
        joinedPath(data,showDepPath){
            var label = data.fullName;
            if (showDepPath && data.deptPathName){
                label += '[' + data.deptPathName + ']';
            }
            let obj = {
                value:data.userId,
                label:label
            }
            return obj;
        },
    },
    watch: {
        value: {
            handler(v) {
                this.curVal = v;
                this.initUser()
            },
            deep: true,
            immediate: true
        }
    },
}
</script>

<style scoped>
.MUser-list {
    display: flex;
    flex-wrap: wrap;
    align-items: center;
    gap: 0.5rem;
}

.MUser-name {
    font-size: .7rem;
    border-radius: 8px;
    background: rgba(242, 242, 242, 1);
    display: flex;
    justify-content: flex-start;
    align-items: center;
    height: 2.344rem;
    padding: 0rem 0.5rem;
    line-height: 2.344rem;
    display: flex;
    align-items: center;
    position: relative;
}

.MUser-fullName {
    line-height: 19.6px;
    color: rgba(0, 0, 0, 0.65);
}

.user-icon {
    width:1.25rem;
    height:1.25rem;
    background: rgba(66, 133, 244, 1);
    display: flex;
    border-radius: 50%;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    color: #fff;
    line-height: 18px;
    text-align: center;
    margin-right: 0.2rem;
}

.user-del {
    position: absolute;
    right: -0.3rem;
    top: -1rem;
    color: rgba(255, 81, 81, 1);
}

.MUser-chang {
    width: 2.344rem;
    height: 2.344rem;
    line-height: 2.344rem;
    opacity: 1;
    border-radius: 8px;
    background: rgba(245, 246, 249, 1);
    display: flex;
    justify-content: center;
    align-items: center;
    color: rgba(0, 0, 0, 0.5);

}
</style>
